﻿using System.Collections.Generic;
using Bentley.DgnPlatformNET;
using Bentley.GeometryNET;
using Bentley.CIMNET.CIMCore.Elements;
using SolidUtil = Bentley.CIMNET.CIMGeometry.Solid.SolidUtil;
using Bentley.DgnPlatformNET.Elements;
using Bentley.MstnPlatformNET;
using Bentley.CifNET.LinearGeometry;
using System.IO;
using System.Data;
using BIM = Bentley.Interop.MicroStationDGN;
using BMI = Bentley.MstnPlatformNET.InteropServices;
using System;
using Bentley.ECObjects.Instance;
using Bentley.DgnPlatformNET.DgnEC;
using Newtonsoft.Json.Linq;
using System.Linq;
using System.Text.RegularExpressions;
namespace 圆管涵正管节
{
    public enum SolidLineStyle
    {
        连续线 = 0,
        短虚线 = 1,
        中虚线 = 2,
        长虚线 = 3,
        点划线 = 4,
        双点划线 = 6,
    }
    public enum SolidColor
    {
        白色 = 0,
        蓝色 = 129,
        绿色 = 178,
        红色 = 147,
        黄色 = 4,
        莹黄 = 142,
        灰色 = 184,
        青色 = 167,
        紫色 = 141,
    }

    internal class SolidHelper
    {
        public static string WorkSpacePath => ConfigurationManager.GetVariable("Checc_CulvertCustomPath") == null ? "C:\\Program Files\\CCCCLTD\\Highway BIM Solution\\ZJCulvert\\Resources\\" : ConfigurationManager.GetVariable("Checc_CulvertCustomPath");
        public static string LevelAndMatrialJsonFilePath = WorkSpacePath + "Standards\\涵洞\\涵洞_属性图层材质设置_当前值.ini"; // @"d:\涵洞_属性图层材质设置_当前值.ini";
        public static string SeedFilePath => ConfigurationManager.GetVariable("MS_SEEDFILES");

        private static DgnModelRef modelRef = Bentley.MstnPlatformNET.Session.Instance.GetActiveDgnModelRef();
        //public static DgnModel dgnmodel = Bentley.MstnPlatformNET.Session.Instance.GetActiveDgnModel();
        public static double UOR = modelRef.GetModelInfo().UorPerMaster;

        //均为米制单位  //圆盘
        public static CurveVector CreateArcCurveVector(DPoint3d center, DMatrix3d dMatrix3D, double a, double b, CurveVector.BoundaryType boundaryType)
        {
            DgnModel dgnmodel = Bentley.MstnPlatformNET.Session.Instance.GetActiveDgnModel();
            CurveVector cvv = new CurveVector(boundaryType);
            ArcElement arcEle1 = new ArcElement(dgnmodel, null, MeterToUor(center), a * UOR, b * UOR, dMatrix3D, 0, Math.PI * 2);
            CurveVector cv = arcEle1.GetCurveVector();
            CurvePrimitive cp = cv.GetPrimitive(0);
            cvv.Add(cp);
            return cvv;
        }
        //计算字符串中某个字符出现的次数
        public static int SubstringCount(string str, string substring)
        {
            int count = 0;
            if (str.Contains(substring))
            {
                string strReplaced = str.Replace(substring, "");
                count = str.Length - strReplaced.Length;
            }
            return count;
        }
        //string rebarLayerName = SolidHelper.GetRebarOutterD("HRB400", "40");
        //上面是获取HRB400钢筋 标称直径是40的钢筋外径
        public static string GetRebarOutterD(string txt, string nominalDiameter)
        {
            string rebarJsonFilePath =
                System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) +
                @"\rebarConfig.json";
            string jsonString = File.ReadAllText(rebarJsonFilePath);
            JObject jobj = JObject.Parse(jsonString);
            JArray jarray = JArray.Parse(jobj[txt].ToString());

            foreach (JObject ss in jarray)
            {
                if (ss["nominalDiameter"].ToString() == nominalDiameter)
                {
                    return ss["outerDiameter"].ToString();
                }
            }
            return nominalDiameter;
        }
        //获取josn中对应的重量换算weightPerMeter 用于属性重量中
        public static string GetRebarOutterKG(string txt, string outerDiameter)
        {
            string rebarJsonFilePath =
                System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) +
                @"\rebarConfig.json";
            string jsonString = File.ReadAllText(rebarJsonFilePath);
            JObject jobj = JObject.Parse(jsonString);
            JArray jarray = JArray.Parse(jobj[txt].ToString());

            foreach (JObject ss in jarray)
            {
                if (ss["outerDiameter"].ToString() == outerDiameter)
                {
                    return ss["weightPerMeter"].ToString();
                }
            }
            return "7.86";
        }
        //均为米制单位  //圆环
        public static CurveVector CreateTubeCurveVector(DPoint3d center, DMatrix3d dMatrix3D, double R_big, double R_small)
        {
            DgnModel dgnmodel = Bentley.MstnPlatformNET.Session.Instance.GetActiveDgnModel();
            CurveVector cvv_big = new CurveVector(CurveVector.BoundaryType.Inner);
            ArcElement arcEle_big = new ArcElement(dgnmodel, null, MeterToUor(center), R_big * UOR, R_big * UOR, DMatrix3d.Identity, 0, Math.PI * 2);
            CurveVector cv = arcEle_big.GetCurveVector();
            CurvePrimitive cp = cv.GetPrimitive(0);
            cvv_big.Add(cp);

            CurveVector cvv_small = new CurveVector(CurveVector.BoundaryType.Inner);
            ArcElement arcEle_small = new ArcElement(dgnmodel, null, MeterToUor(center), R_small * UOR, R_small * UOR, DMatrix3d.Identity, 0, Math.PI * 2);
            cv = arcEle_small.GetCurveVector();
            cp = cv.GetPrimitive(0);
            cvv_small.Add(cp);

            CurveVector mycv = new CurveVector(CurveVector.BoundaryType.Inner);
            mycv = CurveVector.AreaDifference(cvv_big, cvv_small);

            DTransform3d transform3D = DTransform3d.FromMatrixAndFixedPoint(dMatrix3D, MeterToUor(center));
            mycv.Transform(transform3D);

            //Element ele = DraftingElementSchema.ToElement(dgnmodel, mycv, null);
            //ele.AddToModel();
            return mycv;
        }

        public static DMatrix3d CE单位矩阵(DPoint3d D矩阵原点, DPoint3d D矩阵X轴点, DPoint3d D矩阵Y轴点)
        {
            DMatrix3d rMatrix = new DMatrix3d();
            DVector3d V矩阵原点 = new DVector3d(D矩阵原点);
            DVector3d V矩阵X轴点 = new DVector3d(D矩阵X轴点);
            DVector3d V矩阵Y轴点 = new DVector3d(D矩阵Y轴点);

            DVector3d X轴单位向量 = new DVector3d();
            DVector3d Y轴单位向量 = new DVector3d();
            DVector3d Z轴单位向量 = new DVector3d();
            DVector3d Dnum = new DVector3d();

            //X轴单位向量
            Dnum = DVector3d.Subtract(V矩阵X轴点, V矩阵原点);
            //单位向量
            Dnum.NormalizeInPlace();
            //MessageBox.Show(Convert.ToString(DVector3d.Zero.Distance(Dnum)));
            X轴单位向量 = Dnum;

            //Y轴单位向量
            Dnum = DVector3d.Subtract(V矩阵Y轴点, V矩阵原点);
            //单位向量
            Dnum.NormalizeInPlace();
            //MessageBox.Show(Convert.ToString(DVector3d.Zero.Distance(Dnum)));
            Y轴单位向量 = Dnum;

            //Z轴单位向量
            Dnum = DVector3d.CrossProduct(X轴单位向量.X, X轴单位向量.Y, X轴单位向量.Z, Y轴单位向量.X, Y轴单位向量.Y, Y轴单位向量.Z);
            //单位向量
            Dnum.NormalizeInPlace();
            //MessageBox.Show(Convert.ToString(DVector3d.Zero.Distance(Dnum)));
            Z轴单位向量 = Dnum;

            DVector3d DVX = new DVector3d(X轴单位向量.X, Y轴单位向量.X, Z轴单位向量.X);
            DVector3d DVY = new DVector3d(X轴单位向量.Y, Y轴单位向量.Y, Z轴单位向量.Y);
            DVector3d DVZ = new DVector3d(X轴单位向量.Z, Y轴单位向量.Z, Z轴单位向量.Z);

            rMatrix = DMatrix3d.FromRows(DVX, DVY, DVZ);

            //MessageBox.Show(Convert.ToString(rMatrix.RowX.X + "/" + rMatrix.RowX.Y + "/" + rMatrix.RowX.Z));
            //MessageBox.Show(Convert.ToString(rMatrix.RowY.X + "/" + rMatrix.RowY.Y + "/" + rMatrix.RowY.Z));
            //MessageBox.Show(Convert.ToString(rMatrix.RowZ.X + "/" + rMatrix.RowZ.Y + "/" + rMatrix.RowZ.Z));

            return rMatrix;
        }
        public static DPoint3d MeterToUor(DPoint3d pt)
        {
            return new DPoint3d(pt.X * UOR, pt.Y * UOR, pt.Z * UOR);
        }

        public static DPoint3d UorToMeter(DPoint3d pt)
        {
            return new DPoint3d(pt.X / UOR, pt.Y / UOR, pt.Z / UOR);
        }

        // 矩阵逆变换
        public static DMatrix3d GetDMatrix3dform3PtToWorld(DPoint3d P1, DPoint3d P2, DPoint3d P3)
        {
            //计算P3向P1=>P2连线的垂足
            double S12 = P1.Distance(P2);
            double S13 = P1.Distance(P3);
            double S23 = P2.Distance(P3);
            double cosA2 = (S12 * S12 + S23 * S23 - S13 * S13) / (2 * S12 * S23);
            double L = S23 * cosA2;
            LinearElement L21 = new Line(P2, P1);
            //DPoint3d P3垂足 = L21.ProjectPointOnPerpendicular(P3).Coordinates;
            DPoint3d P3垂足 = L21.GetPointAtDistanceOffset(L, 0).Coordinates;
            DVector3d X轴单位向量 = new DVector3d(P2 - P1);
            DVector3d Y轴单位向量 = new DVector3d(P3 - P3垂足);
            DVector3d Z轴单位向量 = DVector3d.CrossProduct(X轴单位向量.X, X轴单位向量.Y, X轴单位向量.Z, Y轴单位向量.X, Y轴单位向量.Y, Y轴单位向量.Z);
            X轴单位向量.NormalizeInPlace();
            Y轴单位向量.NormalizeInPlace();
            Z轴单位向量.NormalizeInPlace();
            DVector3d DVX = new DVector3d(X轴单位向量.X, Y轴单位向量.X, Z轴单位向量.X);
            DVector3d DVY = new DVector3d(X轴单位向量.Y, Y轴单位向量.Y, Z轴单位向量.Y);
            DVector3d DVZ = new DVector3d(X轴单位向量.Z, Y轴单位向量.Z, Z轴单位向量.Z);

            DMatrix3d rMatrix = DMatrix3d.FromColumns(DVX, DVY, DVZ);
            return rMatrix;
        }
        /*
       M:原点
       N:指向点
       LL:指定延长的长度
       */

        public static  DPoint3d GetNformMNAndLL(DPoint3d M, DPoint3d N, double LL)
        {
            DPoint3d PT = new DPoint3d();

            DVector3d VM = new DVector3d(M);
            DVector3d VN = new DVector3d(N);

            DVector3d MN = new DVector3d();

            MN = DVector3d.Subtract(VN, VM);

            double len = VM.Distance(VN);
            double Bei = (LL / len);

            MN.ScaleInPlace(Bei);
            VN = DVector3d.Add(MN, VM);
            PT = new DPoint3d(VN);

            return PT;
        }
        // 矩阵变换到P1=>p2 为X轴方向   垂足=>p3为Y轴方向
        public static DMatrix3d GetDMatrix3dform3Pt(DPoint3d P1, DPoint3d P2, DPoint3d P3)
        {
            //计算P3向P1=>P2连线的垂足
            double S12 = P1.Distance(P2);
            double S13 = P1.Distance(P3);
            double S23 = P2.Distance(P3);
            double cosA2 = (S12 * S12 + S23 * S23 - S13 * S13) / (2 * S12 * S23);
            double L = S23 * cosA2;
            LinearElement L21 = new Line(P2, P1);
            //DPoint3d P3垂足 = L21.ProjectPointOnPerpendicular(P3).Coordinates;
            DPoint3d P3垂足 = L21.GetPointAtDistanceOffset(L, 0).Coordinates;
            DVector3d X轴单位向量 = new DVector3d(P2 - P1);
            DVector3d Y轴单位向量 = new DVector3d(P3 - P3垂足);
            DVector3d Z轴单位向量 = DVector3d.CrossProduct(X轴单位向量.X, X轴单位向量.Y, X轴单位向量.Z, Y轴单位向量.X, Y轴单位向量.Y, Y轴单位向量.Z);
            X轴单位向量.NormalizeInPlace();
            Y轴单位向量.NormalizeInPlace();
            Z轴单位向量.NormalizeInPlace();
            DVector3d DVX = new DVector3d(X轴单位向量.X, Y轴单位向量.X, Z轴单位向量.X);
            DVector3d DVY = new DVector3d(X轴单位向量.Y, Y轴单位向量.Y, Z轴单位向量.Y);
            DVector3d DVZ = new DVector3d(X轴单位向量.Z, Y轴单位向量.Z, Z轴单位向量.Z);

            DMatrix3d rMatrix = DMatrix3d.FromRows(DVX, DVY, DVZ);

            return rMatrix;
        }

        // 三个不共面向量, 返回矩阵=>原模型三个向量方向的长度保持不变
        /*  举例: 下面例程相当于将ele的Z轴方向指向了DPoint3d(0,1,1),其长度与原Z轴方向长度保持一致
         *  Element ele = checcSmartSolid.CreateArcIncludeArc();
            DVector3d dv_x = new DVector3d(1, 0, 0);
            DVector3d dv_y = new DVector3d(0, 1, 0);
            DVector3d dv_z = new DVector3d(0, 1, 1);
            DMatrix3d dma = SolidHelper.GetDMatrix3dform3Dv(dv_x, dv_y, dv_z);
            DTransform3d trans = DTransform3d.FromMatrixAndFixedPoint(dma, new DPoint3d());
            TransformInfo transinfro=new TransformInfo(trans);
            ele.ApplyTransform(transinfro);
         */
        public static DMatrix3d GetDMatrix3dform3Dv(DVector3d DV_x, DVector3d DV_Y, DVector3d DV_Z)
        {
            DVector3d X轴单位向量 = DV_x;
            DVector3d Y轴单位向量 = DV_Y;
            DVector3d Z轴单位向量 = DV_Z;
            X轴单位向量.NormalizeInPlace();
            Y轴单位向量.NormalizeInPlace();
            Z轴单位向量.NormalizeInPlace();
            DVector3d DVX = new DVector3d(X轴单位向量.X, Y轴单位向量.X, Z轴单位向量.X);
            DVector3d DVY = new DVector3d(X轴单位向量.Y, Y轴单位向量.Y, Z轴单位向量.Y);
            DVector3d DVZ = new DVector3d(X轴单位向量.Z, Y轴单位向量.Z, Z轴单位向量.Z);
            DMatrix3d rMatrix = DMatrix3d.FromRows(DVX, DVY, DVZ);
            return rMatrix;
        }

        static void CimMoveElement(CimGraphicElement element, DPoint3d origin, DPoint3d target)
        {
            DTransform3d transform = DTransform3d.FromTranslation(DPoint3d.Subtract(target, origin));
            element.ApplyTransform(new TransformInfo(transform));
        }

        static void msMoveElement(Element element, DPoint3d origin, DPoint3d target)
        {
            DTransform3d transform = DTransform3d.FromTranslation(DPoint3d.Subtract(target, origin));
            element.ApplyTransform(new TransformInfo(transform));
        }

        //获取cv起点 米单位
        public static DPoint3d GetCurveVectorSP(CurveVector cv)
        {
            CurvePrimitive cp = cv.GetPrimitive(0);
            CurveVector curCV = new CurveVector(CurveVector.BoundaryType.None);
            curCV.Add(cp);
            LinearElement le = LinearElement.CreateFromCurveVector(curCV, true);
            DPoint3d sp = le.StartPoint.Coordinates;
            return sp;
        }
        //获取cv终点 米单位
        public static DPoint3d GetCurveVectorEP(CurveVector cv)
        {
            CurvePrimitive cp = cv.GetPrimitive(cv.Count - 1);
            CurveVector curCV = new CurveVector(CurveVector.BoundaryType.None);
            curCV.Add(cp);
            LinearElement le = LinearComplex.CreateFromCurveVector(curCV, false);
            DPoint3d ep = le.EndPoint.Coordinates;
            return ep;
        }

        //获取cv起点的矩阵
        public static DMatrix3d GetCurveVectorSPdma(CurveVector cv)
        {
            DMatrix3d rMatrix = DMatrix3d.Identity;
            CurvePrimitive cp = cv.GetPrimitive(0);
            CurveVector curCV = new CurveVector(CurveVector.BoundaryType.None);
            curCV.Add(cp);
            LinearElement le = LinearElement.CreateFromCurveVector(curCV, false);
            DPoint3d sp = le.StartPoint.Coordinates;
            DPoint3d sp_x = le.GetPointAtDistanceOffset(0, 1).Coordinates;
            DPoint3d sp_y = new DPoint3d(sp.X, sp.Y, sp.Z + 10);
            rMatrix = GetDMatrix3dform3Pt(sp, sp_x, sp_y);
            double l = le.Length;
            return rMatrix;
        }


        //获取cv终点矩阵
        public static DMatrix3d GetCurveVectorEPdma(CurveVector cv)
        {
            DMatrix3d rMatrix = DMatrix3d.Identity;
            CurvePrimitive cp1 = cv.GetPrimitive(cv.Count - 1);
            CurveVector curCV = new CurveVector(CurveVector.BoundaryType.None);
            curCV.Add(cp1);
            LinearElement le = LinearComplex.CreateFromCurveVector(curCV, false);
            DPoint3d ep = le.EndPoint.Coordinates;
            DPoint3d ep_x = le.GetPointAtDistanceOffset(le.Length, 1).Coordinates;
            DPoint3d ep_y = new DPoint3d(ep.X, ep.Y, ep.Z + 10); //le.GetPointAtDistanceOffset(le.Length-0.001, 0).Coordinates;
            rMatrix = GetDMatrix3dform3Pt(ep, ep_x, ep_y);
            return rMatrix;
        }

        //顺着path制作体
        public static Element CreateSweep(CurveVector startProfile, CurveVector path, string levelname, int color, int lineStyle, int lineWidth, DgnModel dgnModel)
        {
            SolidKernelEntity pSolid = null;
            try
            {
                if (SolidUtil.Create.BodyFromSweep(out pSolid, startProfile, path, dgnModel, false, false, false, null, null, null, null) == BentleyStatus.Success)
                {
                    //Convert1.BodyToElement(out Element ele, pSolid, null, dgnModel);
                    //setElementByLevel(levelname, color, lineStyle, lineWidth, ele);
                    //return ele;
                }
            }
            catch (Exception)
            {

            }
            return null;
        }

        //顺着path制作体
        public static Element CreateSweepbak(CurveVector startProfile, CurveVector path, string levelname, int color, int lineStyle, int lineWidth, DgnModel dgnModel)
        {
            SolidKernelEntity pSolid = null;
            try
            {
                //SolidUtil.Create.BodyFromSweep(
                if (SolidUtil.Create.BodyFromSweep(out pSolid, startProfile, path, dgnModel, false, false, false, null, null, null, null) == BentleyStatus.Success)
                {
                    //SolidUtil.Properties.BodyMassProperties(out double volumeOut, out double peripheryOut, out DPoint3d centroidOut, out double[][] inertiaOut, pSolid, 0.001);
                    //Convert1.BodyToElement(out Element ele, pSolid, null, dgnModel);
                    //setElementByLevel(levelname, color, lineStyle, lineWidth, ele);
                    //ele.AddToModel();
                    //return ele;
                }
            }
            catch (Exception)
            {

            }
            return null;
        }


        public static SolidKernelEntity CreateSlab(double length, double width, double height, DgnModelRef modelRef1)
        {
            length *= UOR;
            width *= UOR;
            height *= UOR;
            SolidKernelEntity pSolid = null;
            try
            {
                if (SolidUtil.RapidSolidCreate.MakeSlabBody(out pSolid, length, width, height, modelRef1) == BentleyStatus.Success)
                {
                    //SolidUtil.Properties.BodyMassProperties(out double volumeOut, out double peripheryOut, out DPoint3d centroidOut, out double[][] inertiaOut, pSolid, 0.001);
                    return pSolid;
                }
            }
            catch (Exception)
            {

            }
            return null;
        }

        public static Element CreateConeElement(double basePrim, double baseSec, double topPrim, double topSec, double height, DgnModel dgnmodel1)
        {
            DgnModelRef modelRef1 = dgnmodel1;
            basePrim *= UOR;
            baseSec *= UOR;
            topPrim *= UOR;
            topSec *= UOR;
            height *= UOR;
            SolidKernelEntity pSolid = null;
            try
            {
                if (SolidUtil.RapidSolidCreate.MakeEllipticalConeBody(out pSolid,  basePrim,  baseSec,  topPrim,  topSec,  height, modelRef1) == BentleyStatus.Success)
                {
                    //SolidUtil.Properties.BodyMassProperties(out double volumeOut, out double peripheryOut, out DPoint3d centroidOut, out double[][] inertiaOut, pSolid, 0.001);
                    //Convert1.BodyToElement(out Element ele, pSolid, null, dgnmodel1);
                   // return ele;
                }
            }
            catch (Exception)
            {

            }
            return null;
        }
        public static SolidKernelEntity CreateConePsolid(double basePrim, double baseSec, double topPrim, double topSec, double height, DgnModel dgnmodel1)
        {
            DgnModelRef modelRef1 = dgnmodel1;
            basePrim *= UOR;
            baseSec *= UOR;
            topPrim *= UOR;
            topSec *= UOR;
            height *= UOR;
            SolidKernelEntity pSolid = null;
            try
            {
                if (SolidUtil.RapidSolidCreate.MakeEllipticalConeBody(out pSolid, basePrim, baseSec, topPrim, topSec, height, modelRef1) == BentleyStatus.Success)
                {
                    return pSolid;
                }
            }
            catch (Exception)
            {

            }
            return null;
        }

        //挤压实体 Z方向
        public static Element CreateExtrusion(CurveVector startProfile, double distance, string levelname, int color, int lineStyle, int lineWidth,DgnModel dgnModel)
        {
            DgnModel dgnmodel = Bentley.MstnPlatformNET.Session.Instance.GetActiveDgnModel();
            distance = distance * UOR;
            DgnModelRef modelRef1 = dgnModel;
            SolidKernelEntity pSolid = null;
            try
            {
                if (SolidUtil.Create.BodyFromExtrusion(out pSolid, startProfile, distance, modelRef1, new DVector3d(0, 0, 1), false, null) == BentleyStatus.Success)
                {
                    //SolidUtil.Properties.BodyMassProperties(out double volumeOut, out double peripheryOut, out DPoint3d centroidOut, out double[][] inertiaOut, pSolid, 0.001);
                    //Convert1.BodyToElement(out Element ele, pSolid, null, dgnModel);
                    string hxd=dgnmodel.ModelName;
                    //setElementByLevel(levelname, color, lineStyle, lineWidth, ele);
                    //ele.AddToModel();
                    //return ele;
                }
            }
            catch (Exception)
            {

            }
            return null;
        }

        //挤压实体
        public static Element CreateExtrusionWithDir(CurveVector startProfile, double distance, DgnModel dgnModel,DVector3d dir)
        {
            distance = distance * UOR;
            DgnModelRef modelRef1 = dgnModel;
            SolidKernelEntity pSolid = null;
            try
            {
                if (SolidUtil.Create.BodyFromExtrusion(out pSolid, startProfile, distance, modelRef1, dir, false, null) == BentleyStatus.Success)
                {
                    //Convert1.BodyToElement(out Element ele, pSolid, null, dgnModel);                 
                    //return ele;
                }
            }
            catch (Exception)
            {

            }
            return null;
        }


        //顺着path制作体
        public static SolidKernelEntity CreateExtrusionPsolid(CurveVector startProfile, double distance, string levelname, int color, int lineStyle, int lineWidth, DgnModel dgnModel)
        {
            distance = distance * UOR;
            DgnModelRef modelRef1 = dgnModel;
            SolidKernelEntity pSolid = null;
            try
            {
                if (SolidUtil.Create.BodyFromExtrusion(out pSolid, startProfile, distance, modelRef1, new DVector3d(0, 0, 1), false, null) == BentleyStatus.Success)
                {
                    return pSolid;
                }
            }
            catch (Exception)
            {

            }
            return null;
        }


        /// <summary>
        /// CimLineElement
        /// </summary>
        public static CimLineElement doCreateCimLineElement(DPoint3d SP, DPoint3d EP)
        {
            DPoint3d start = new DPoint3d(SP.X * UOR, SP.Y * UOR, 0 * UOR);
            DPoint3d end = new DPoint3d(EP.X * UOR, EP.Y * UOR, 0 * UOR);
            CimLineElement element = new CimLineElement(start, end, modelRef);
            return element;
        }

        /// <summary>
        /// 新建图层
        /// </summary>
        /// <param name="levelname">层名</param>
        /// <param name="color">颜色</param>
        public static void CreateLevel(string levelname, int color, int lineStyle, int lineWidth)
        {
            bool isHave = false; //已经存在该层名
            //创建新图层层
            FileLevelCache lvlCachaActive = Session.Instance.GetActiveDgnFile().GetLevelCache();
            LevelHandleCollection lhc = lvlCachaActive.GetHandles();
            EditLevelHandle updateLevel = null;
            foreach (LevelHandle level in lhc)
            {
                if (level.Name == levelname)
                {
                    isHave = true;
                    updateLevel = level.GetEditHandle();
                    break;
                }
            }

            if (isHave == false)
            {
                EditLevelHandle newLevel = lvlCachaActive.CreateLevel(levelname);
                LevelDefinitionColor clo = new LevelDefinitionColor((uint)color, Session.Instance.GetActiveDgnFile());
                newLevel.SetByLevelColor(clo);
                LineStyleParameters lspar = null;
                LevelDefinitionLineStyle LS = new LevelDefinitionLineStyle(lineStyle, lspar, Session.Instance.GetActiveDgnFile());
                newLevel.SetByLevelLineStyle(LS);
                newLevel.ByLevelWeight = (uint)lineWidth;
                lvlCachaActive.Write();
            }
            else
            {
                LevelDefinitionColor levelColor = new LevelDefinitionColor((uint)color, Session.Instance.GetActiveDgnFile());
                updateLevel.SetByLevelColor(levelColor);
                LineStyleParameters lspar = null;
                LevelDefinitionLineStyle LS = new LevelDefinitionLineStyle(lineStyle, lspar, Session.Instance.GetActiveDgnFile());
                updateLevel.SetByLevelLineStyle(LS);
                updateLevel.ByLevelWeight = (uint)lineWidth;
                lvlCachaActive.Write();
            }
        }

        //图层打开与关闭
        public static void SetLevelDisplay(string levelname,bool isDisplay)
        {
            bool isHave = false;
            FileLevelCache lvlCachaActive = Session.Instance.GetActiveDgnFile().GetLevelCache();
            LevelHandleCollection lhc = lvlCachaActive.GetHandles();
            EditLevelHandle updateLevel = null;
            foreach (LevelHandle level in lhc)
            {
                if (level.Name == levelname)
                {
                    isHave = true;
                    updateLevel = level.GetEditHandle();
                    break;
                }
            }
            if (isHave)
            {
                updateLevel.Display = isDisplay;
                lvlCachaActive.Write();
            }
        }

        public static DgnModel CreateModel(string modelName, DgnModelType modelType, bool is3D, int annotationScaleFactor)
        {
            DgnFile dgnFile = Session.Instance.GetActiveDgnFile();
            ModelId modelId = new ModelId();
            try
            {
                modelId = dgnFile.FindModelIdByName(modelName);
            }
            catch
            {
            }
            if (modelId != -2)
            {
                //DgnModel dgnModel1 = dgnFile.FindLoadedModelById(modelId);
                //dgnFile.DeleteModel(dgnModel1);
                SetAnnotationScale(1D, modelName);
                return dgnFile.FindLoadedModelById(modelId);
            }

            DgnModelStatus status;
            //DgnModel Model = Session.Instance.GetActiveDgnModel();
            DgnModel dgnModel = dgnFile.CreateNewModel(out status, modelName, modelType, is3D, null);
            //Model.GetDgnModel();

            ModelInfo modelInfo = dgnModel.GetModelInfo();
            modelInfo.AnnotationScaleFactor = annotationScaleFactor;
            dgnModel.SetModelInfo(modelInfo); //应用属性
            dgnModel.SaveModelSettings();
            return dgnModel;
        }
        /// <summary>
        /// 所有注释单元生成后调用
        /// </summary>
        /// <param name="BL"></param>
        public static void SetAnnotationScale(double BL, string modelName)
        {
            //设置模型注释比例, 适用于当前模型已添加文字或者注释单元, 可以直接看到修改比例后的效果
            BIM.Application myApp = BMI.Utilities.ComApp;
            BIM.ModelReference modelReference = myApp.ActiveDesignFile.Models[modelName];
            BIM.PropertyHandler phOld = myApp.CreatePropertyHandler(modelReference);
            if (phOld.SelectByAccessString("AnnotationScale") == true)
            {
                string DD = Convert.ToString(BL);
                object obj = DD;
                phOld.SetValue(ref obj);
            }
        }
        /// <summary>
        /// 新建图层, 并设置为激活层, 赋予给元素
        /// </summary>
        /// <param name="levelname">层名</param>
        /// <param name="color">颜色</param>
        public static void setElementByLevel(string levelname, int color, int lineStyle, int lineWidth, Element ele)
        {
            CreateLevel(levelname, color, lineStyle, lineWidth);
            FileLevelCache lvlCachaActive = Session.Instance.GetActiveDgnFile().GetLevelCache();
            ElementPropertiesSetter elePropSet = new ElementPropertiesSetter();
            LevelHandle levelhadle = lvlCachaActive.GetLevelByName(levelname);
            elePropSet.SetLevel(levelhadle.LevelId);
            uint bylevel = 4294967295;//16进制(FFFFFFFF)转10进制
            elePropSet.SetColor(bylevel);
            elePropSet.SetWeight(bylevel);
            LineStyleParameters lspar = null;
            int bylevels = 2147483647;//16进制(7FFFFFFF)转10进制
            elePropSet.SetLinestyle(Convert.ToInt32(bylevels), lspar);
            elePropSet.Apply(ele);
        }
        //计算转向  返回"左" "右"
        public static string TurnLR(DPoint3d o, DPoint3d s, DPoint3d e)
        {
            double x1 = s.X, y1 = s.Y;
            double x2 = o.X, y2 = o.Y;
            double x3 = e.X, y3 = e.Y;
            double A = AtoX轴(o, e) - AtoX轴(s, o);
            //认为转角不能大于180
            if (A > 0)
            {
                if (A < Math.PI)
                {
                    return "左";
                }
                else
                {
                    return "右";
                }
            }
            else
            {
                if (Math.Abs(A) < Math.PI)
                {
                    return "右";
                }
                else
                {
                    return "左";
                }
            }
        }

        //计算与X轴正向夹角
        public static double AtoX轴(DPoint3d sp, DPoint3d ep)
        {
            double X0 = sp.X;
            double Y0 = sp.Y;
            double X1 = ep.X;
            double Y1 = ep.Y;
            double AA;
            if (X1 == X0)
            {
                if (Y1 > Y0)
                {
                    AA = Math.PI / 2;
                }
                else
                {
                    AA = Math.PI * 3 / 2;
                }

            }
            else
            {
                AA = Math.Abs(Math.Atan((Y1 - Y0) / (X1 - X0)));
                if (X1 >= X0 && Y1 >= Y0)
                {
                    AA = AA + 0;
                }
                else if (X1 >= X0 && Y1 < Y0)
                {
                    AA = 2 * Math.PI - AA;
                }
                else if (X1 < X0 && Y1 < Y0)
                {
                    AA = Math.PI + AA;
                }
                else
                {
                    AA = Math.PI - AA;
                }
            }
            return AA;
        }
        public static DPoint3d LE交点(LinearElement LE1, LinearElement LE2)
        {
            DPoint3d pt = new DPoint3d();
            if (LE1 == null || LE2 == null)
            {
                return pt;
            }
            CurveVector cveVcr1 = LE1.GetCurveVector();
            CurveVector cveVcr2 = LE2.GetCurveVector();
            CurveVector cveVcrInter1 = CurveVector.Create(CurveVector.BoundaryType.None), cveVcrInter2 = CurveVector.Create(CurveVector.BoundaryType.None);
            CurveCurve.IntersectionsXY(cveVcrInter1, cveVcrInter2, cveVcr1, cveVcr2);
            cveVcrInter1.GetStartPoint(out pt);
            return pt;
        }

        public static void WriteDataBlockToElement(ushort dataBlockId, ref Element element, string dataBlockString)
        {
            WriteDataBlock dataBlock = new WriteDataBlock();
            dataBlock.WriteString(dataBlockString);
            element.AppendLinkage(dataBlockId, dataBlock);
            //element.ReplaceInModel(element);
        }

        public static void DeleteDataBlockByID(ushort dataBlockId, ref Element element)
        {
            if (element == null)
            {
                return;
            }
            element.DeleteLinkage(dataBlockId);
        }

        public static string GetDatablockByID(ushort dataBlockId, ref Element element)
        {
            string blockstring = "";
            using (ReadDataBlock data = element.GetLinkage(dataBlockId))
            {
                if (data != null) blockstring = data.ReadString();
            }
            return blockstring;
        }

        public static CurveVector BsplineCurvertor(CurveVector cv)
        {
            CurvePrimitive cp = CurvePrimitive.CreateChildCurveVectorCopyFromSource(cv);
            MSInterpolationCurve mc = cp.GetInterpolationCurve();
            MSBsplineCurve msc = mc.ConvertToBspline();
            CurvePrimitive curvePri = CurvePrimitive.CreateBsplineCurve(msc);
            BSplineCurveElement ele = DraftingElementSchema.ToElement(Bentley.MstnPlatformNET.Session.Instance.GetActiveDgnModel(), curvePri, null) as BSplineCurveElement;
            return ele.GetCurveVector();
        }

        public static  BSplineCurveElement getBSele(List<DPoint3d> lstpts)
        {
            //DgnModel dgnModel = Session.Instance.GetActiveDgnModel();

            DVector3d[] tangents = { new DVector3d(0, 0), new DVector3d(0, 0) };
            MSInterpolationCurve curve = MSInterpolationCurve.CreateFromPointsAndEndTangents(lstpts.ToArray(), true, 0.01, tangents, false, false, false, false);
            BSplineCurveElement curveElem = new BSplineCurveElement(Session.Instance.GetActiveDgnModel(), null, curve);
            return curveElem;
        }
        public static BSplineCurveElement getBSele(List<DPoint3d> lstpts,DgnModel dgnModel)
        {
            //DgnModel dgnModel = Session.Instance.GetActiveDgnModel();

            DVector3d[] tangents = { new DVector3d(0, 0), new DVector3d(0, 0) };
            MSInterpolationCurve curve = MSInterpolationCurve.CreateFromPointsAndEndTangents(lstpts.ToArray(), true, 0.01, tangents, false, false, false, false);
            BSplineCurveElement curveElem = new BSplineCurveElement(dgnModel, null, curve);
            return curveElem;
        }
        //输入为米制单位
        public static Element  MoveElement(Element element, DPoint3d origin, DPoint3d target)
        {
            //DTransform3d tran =new DTransform3d();
            //tran.Translation = DPoint3d.Subtract(target, origin);

            DTransform3d transform = DTransform3d.FromTranslation(DPoint3d.Subtract(MeterToUor(target), MeterToUor(origin)));
            element.ApplyTransform(new TransformInfo(transform));
            return element;
        }

        //获取体积 立方米
        public static double getVolume(Element element, BIM.Application app)
        {
            double volume = 0;
            long eleId = element.ElementId;
            BIM.PropertyHandler phOld = app.CreatePropertyHandler(app.ActiveModelReference.GetElementByID(ref eleId));
            if (phOld.SelectByAccessString("Volume") == true)
            {
                volume = Convert.ToDouble(phOld.GetValue());
            }
            return volume;
        }



        //获取体积 立方米
        public static double getVolume(Element element)
        {
            DgnModel dgnmodel = Bentley.MstnPlatformNET.Session.Instance.GetActiveDgnModel();
            DgnECInstanceCollection collection = DgnECManager.Manager.GetElementProperties(element, ECQueryProcessFlags.SearchAllClasses);
            double volume = 0;
            foreach (IDgnECInstance instance in collection)
            {
                //MessageCenter.Instance.StatusMessage = "EC class " + instance.ClassDefinition.Name + " evaluated";
                IECPropertyValue result = instance.GetPropertyValue("Volume");
                if (null != result)
                {
                    if (result.TryGetDoubleValue(out volume))
                    {
                        VolumeFormatter formatter = new VolumeFormatter(dgnmodel);
                        formatter.ShowUnitLabel = true;
                        //MessageCenter.Instance.StatusMessage = "Volume: " + formatter.ToString(volume);
                    }
                }
            }
            return volume/UOR/UOR/UOR;
        }
        //获取面积 平方米
        public static double getArea(Element element)
        {
            DgnModel dgnmodel = Bentley.MstnPlatformNET.Session.Instance.GetActiveDgnModel();
            DgnECInstanceCollection collection = DgnECManager.Manager.GetElementProperties(element, ECQueryProcessFlags.SearchAllClasses);
            double area = 0;
            foreach (IDgnECInstance instance in collection)
            {
                //MessageCenter.Instance.StatusMessage = "EC class " + instance.ClassDefinition.Name + " evaluated";
                IECPropertyValue result = instance.GetPropertyValue("SurfaceArea");
                if (null != result)
                {
                    if (result.TryGetDoubleValue(out area))
                    {
                        VolumeFormatter formatter = new VolumeFormatter(dgnmodel);
                        formatter.ShowUnitLabel = true;
                        //MessageCenter.Instance.StatusMessage = "Volume: " + formatter.ToString(volume);
                    }
                }
            }
            return area / UOR / UOR;
        }


 
        //获取土木材质列表
        public static List<string> GetCivilMaterialList(string unparsed)
        {
            DgnFile dgnFile = Session.Instance.GetActiveDgnFile();//定义当前激活的文件信息
            DgnModel dgnModel = Session.Instance.GetActiveDgnModel();//定义当前激活的模型空间
            DgnModelRef dgnModelRef = dgnModel;
            double uorPerMas = Session.Instance.GetActiveDgnModel().GetModelInfo().UorPerMaster;//获取主单位与分辨率单位的比值

            PaletteInfo[] palInfo = MaterialManager.GetPalettesInDgnLib(dgnFile);   //获取当前所有材质盘
            if (palInfo.Length < 1)//判断是否获取到材料图表
            {
                MessageCenter.Instance.ShowInfoMessage("Can't get palette", null, true);//输出错误信息
                return null;//返回
            }

            List<string> civilNames = new List<string>();
            List<string> prostructureNames = new List<string>();
            Material[] mat = { };
            for (int i = 0; i < palInfo.Length; i++)//遍历材料图表
            {
                mat= MaterialManager.FindMaterialsInPalette(out MaterialSearchStatus searchstatus, palInfo[i], dgnModelRef,true); //获取所有材料
                foreach (Material item in mat)
                {
                    if (palInfo[i].Name.Contains("prostructure"))
                    {
                        prostructureNames.Add(item.Name);
                    }
                    if (palInfo[i].Name.Contains("Civil"))
                    {
                        civilNames.Add(item.Name);
                    }
                }
            }
            return civilNames;
        }

        //获取钢筋材质列表
        public static List<string> GetStructureMaterialList(string unparsed)
        {
            DgnFile dgnFile = Session.Instance.GetActiveDgnFile();//定义当前激活的文件信息
            DgnModel dgnModel = Session.Instance.GetActiveDgnModel();//定义当前激活的模型空间
            DgnModelRef dgnModelRef = dgnModel;
            double uorPerMas = Session.Instance.GetActiveDgnModel().GetModelInfo().UorPerMaster;//获取主单位与分辨率单位的比值

            PaletteInfo[] palInfo = MaterialManager.GetPalettesInDgnLib(dgnFile);   //获取当前所有材质盘
            if (palInfo.Length < 1)//判断是否获取到材料图表
            {
                MessageCenter.Instance.ShowInfoMessage("Can't get palette", null, true);//输出错误信息
                return null;//返回
            }

            List<string> civilNames = new List<string>();
            List<string> prostructureNames = new List<string>();
            Material[] mat = { };
            for (int i = 0; i < palInfo.Length; i++)//遍历材料图表
            {
                mat = MaterialManager.FindMaterialsInPalette(out MaterialSearchStatus searchstatus, palInfo[i], dgnModelRef, true); //获取所有材料
                foreach (Material item in mat)
                {
                    if (palInfo[i].Name.Contains("prostructure"))
                    {
                        prostructureNames.Add(item.Name);
                    }
                    if (palInfo[i].Name.Contains("Civil"))
                    {
                        civilNames.Add(item.Name);
                    }
                }
            }
            return prostructureNames;
        }

        //赋予材质
        public static void ElementAttachMaterial(DisplayableElement element,string materialName)
        {
            MaterialId id = new MaterialId(materialName);//查找名为Pavers BC2的材料
            MaterialPropertiesExtension propertiesExtension = MaterialPropertiesExtension.GetAsMaterialPropertiesExtension(element);//为拉伸实体元素设置材料属性 
            propertiesExtension.AddMaterialAttachment(id);//添加嵌入的材料信息
            propertiesExtension.StoresAttachmentInfo(id);//保存拉伸实体元素的材料信息 
            propertiesExtension.ReplaceInModel(element);//替换实体
            //propertiesExtension.AddToModel();//替换实体
        }

        public static List<DPoint3d> LE交点集(LinearElement LE1, LinearElement LE2)
        {
            List<DPoint3d> list = new List<DPoint3d>();
            if (LE1 == null || LE2 == null)
            {
                return list;
            }
            CurveVector cveVcr1 = LE1.GetCurveVector();
            CurveVector cveVcr2 = LE2.GetCurveVector();
            CurveVector cveVcrInter1 = CurveVector.Create(CurveVector.BoundaryType.None), cveVcrInter2 = CurveVector.Create(CurveVector.BoundaryType.None);
            CurveCurve.IntersectionsXY(cveVcrInter1, cveVcrInter2, cveVcr1, cveVcr2);
            cveVcrInter1.GetStartEnd(out DPoint3d ptA,out DPoint3d ptB);
            list.Add(DPoint3d.Zero);
            list.Add(ptA);
            list.Add(ptB);
            return list;
        }


        //获取涵洞初始化文件的值, txts为按顺序的key值, rebarName 为json文件中的"Number"值
        //举例:
        //string[] strings ={"RebarData", "CircularCulvert_TubeCoupling", "RebarConfigs" };
        //string rebarLayerName = SolidHelper.GetINIvalue(strings, "1");
        //上面是获取1号钢筋的图层名
        public static string GetINIvalue(string[] txts, string rebarName)
        {
            string jsonString = File.ReadAllText(LevelAndMatrialJsonFilePath);
            JObject obj = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(jsonString);
            string jarrayTXT = "";
            switch (txts.Length)
            {
                case 1:
                    jarrayTXT = obj[txts[0]].ToString();
                    break;
                case 2:
                    jarrayTXT = obj[txts[0]][txts[1]].ToString();
                    break;
                case 3:
                    jarrayTXT = obj[txts[0]][txts[1]][txts[2]].ToString();
                    break;
                case 4:
                    jarrayTXT = obj[txts[0]][txts[1]][txts[2]][txts[3]].ToString();
                    break;
                case 5:
                    jarrayTXT = obj[txts[0]][txts[1]][txts[2]][txts[3]][txts[4]].ToString();
                    break;
                default:return "";
            }
            if (rebarName=="")
            {
                return jarrayTXT;
            }
            else
            {
                var rebarObj=JArray.Parse(jarrayTXT);
                foreach (JObject ss in rebarObj)  //查找某个字段与值
                {
                    if (ss["Number"].ToString() == rebarName)
                    {
                        return ss["LayerName"].ToString();
                    }
                }
            }
            return "";
        }



        //赋予元素datablock
        public static StatusInt AppendLinkageToElement(ushort s_linkageId, ref Element element, WriteDataBlock dataBlock)
        {
            if (element == null)
            {
                return StatusInt.Error;
            }
            return element.AppendLinkage(s_linkageId, dataBlock);
        }
        public static StatusInt DeleteLinkageByID(ushort linkageId, ref Element element)
        {
            if (element == null)
            {
                return StatusInt.Error;
            }
            return element.DeleteLinkage(linkageId);
        }

        public static void SetDatablock(ushort linkageId, ref Element element, string dataBlockString)
        {
            WriteDataBlock dataBlock = new WriteDataBlock();
            dataBlock.WriteString(dataBlockString);
            AppendLinkageToElement(linkageId, ref element, dataBlock);
            //element.ReplaceInModel(element);
        }

        public static string GetDatablock(ushort linkageId, ref Element element)
        {
            string blockstring = "";
            using (ReadDataBlock data = element.GetLinkage(linkageId))
            {
                if (data != null) blockstring = data.ReadString();
            }
            return blockstring;
        }

        //计算格式数据, 某一列的和
        /*dataTXT 格式举例
         *  string dataTXT = "a_string,b_double,c_double,d_double,e_double";
            txt += "\r\n" + "1,2,3,4,5";
            txt += "\r\n" + "1,2,3,4,5";
            txt += "\r\n" + "1,2,3,4,5";
            txt += "\r\n" + "1,2,3,4,5";

            Console.WriteLine("a总和:"+dt.Compute("sum(C3)","C2='a'"));
            Console.WriteLine("b总和:"+dt.Compute("sum(C3)","C2='b'"));

        */

        //如果某列 colName_if=value 对colName_sum列进行求和
        public static string CalColumnSum(string dataTXT,string colName_sum, string colName_if, string value)
        {
            try
            {
                DataTable dt = StringToDatatable(dataTXT);
                string exp = "sum(" + colName_sum + ")";
                object sum = dt.Compute(exp, colName_if + "=" + "'" + value + "'");
                return sum.ToString();
            }
            catch
            {
            }
            return "";
        }

        //格式数据写入DataTable: 第一行为字段名称(name_type), 后面各行为数据
        public static DataTable StringToDatatable(string dataString)
        {
            DataTable dt = new DataTable();
            string[] strRow = { "\r\n" };    //分解行的字符串
            string[] rowTXT = dataString.Split(strRow, StringSplitOptions.None);
            //写表头字段
            string[] getAry = rowTXT[0].Split(',');
            int col = getAry.Length;
            for (int j = 0; j < col; j++)
            {
                string[] strs = getAry[j].Split('_');
                if (strs[1].Contains("string"))
                   dt.Columns.Add(strs[0], typeof(string));
                else
                   dt.Columns.Add(strs[0], typeof(double));
            }
            //写各行数据
            for (int i = 1; i < rowTXT.Length; i++)
            {
                if (rowTXT[i].Contains(","))
                {
                    getAry = rowTXT[i].Split(',');
                    col = getAry.Length;
                    DataRow dr = dt.NewRow();
                    for (int n = 0; n < col; n++)
                    {
                        dr[n] = getAry[n];
                    }
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }

        public static void CreateDgnFile(string filePath)
        {
            DgnDocument dgnDoc = DgnDocument.CreateForNewFile(out DgnFileStatus status, filePath, "", 0, "", DgnDocument.OverwriteMode.Always, DgnDocument.CreateOptions.Default);//用DgnDocument对象表示在文件中声明的新文件 
            if (dgnDoc != null)//判断文件是否声明成功
            {
                StatusInt statusInt = dgnDoc.OnNewFileCreated();//声明文件后调用，允许文档管理器将文件添加到储存库中，若该文件只是临时文件则无需调用
                if (statusInt == StatusInt.Success)//判断是否成功
                {
                    DgnFile dgnFile = Session.Instance.GetActiveDgnFile();//获得当前激活的文件信息
                    SeedData seed = new SeedData(dgnFile, dgnFile.DefaultModelId, SeedCopyFlags.AllData, false);//获得当前文中默认模型的种子信息
                    DgnFileOwner owner = DgnFile.CreateNew(out DgnFileStatus fileStatus, dgnDoc, DgnFileOpenMode.ReadWrite, seed, DgnFileFormatType.V8, true);//基于种子文件（可选），声明一个dgn文件
                    owner.Dispose();//在内存中释放该文件
                }
            }
        }

        public static void ActivateDgnmodel(string modelName)
        {
            //设置模型注释比例, 适用于当前模型已添加文字或者注释单元, 可以直接看到修改比例后的效果
            BIM.Application myApp = BMI.Utilities.ComApp;
            BIM.ModelReference modelReference = myApp.ActiveDesignFile.Models[modelName];
            modelReference.Activate();
        }

        public static void AppendAppDataBlock(ushort s_linkageId, string dataBlockString)
        {
            DgnFile dgnfile = Session.Instance.GetActiveDgnFile();
            ModelId modelId = dgnfile.FindModelIdByName("Default");
            DgnModel dgnModel = dgnfile.FindLoadedModelById(modelId);

            ModelElementsCollection mec = dgnModel.GetElements();
            Element ele = null;
            foreach (Element item in mec)
            {
                if (item.TypeName.Contains("Application Data"))
                {
                    ele = item;
                    break;
                }
            }
            WriteDataBlock dataBlock = new WriteDataBlock();
            dataBlock.WriteString(dataBlockString);
            AppendLinkageToElement(s_linkageId, ref ele, dataBlock);
            ele.ReplaceInModel(ele);
        }

        public static string GetAppDatablock(ushort linkageId)
        {
            string blockstring = "";
            DgnFile dgnfile = Session.Instance.GetActiveDgnFile();
            ModelId modelId = dgnfile.FindModelIdByName("Default");
            DgnModel dgnModel = dgnfile.FindLoadedModelById(modelId);
            ModelElementsCollection mec = dgnModel.GetElements();
            foreach (Element item in mec)
            {
                if (item.TypeName.Contains("Application Data"))
                {
                    using (ReadDataBlock data = item.GetLinkage(linkageId))
                    {
                        if (data != null) blockstring = data.ReadString();
                    }
                    if (blockstring != "") break;
                }
            }
            return blockstring;
        }

        public static List<string> StringSplit(string TXT,string splitTxt)
        {
            string[] sArray = Regex.Split(TXT, splitTxt, RegexOptions.IgnoreCase); //忽略大小写
            return sArray.ToList<string>();
        }

    }
}

